import Toast from '../../components/toast/toast'
const app = getApp()
Page({
  data: {
    imageList: [],
    totalMin: 0,
    totalMax: 0,
    submitDialogShow: false,
    deleteDialogShow: false,
    deleteImageId: -1,
  },
  // 验证提交订单条件
  verifySubmit() {
    this.handleSubmitDialogShow()
    let imageNum = this.data.imageList.length
    if (imageNum > this.data.totalMax) {
      Toast.text({
        message: '已超过提交图片的上限，请减少图片后下载'
      })
    } else if (imageNum < this.data.totalMin) {
      Toast.text({
        message: '请添加图片后下载'
      })
    } else {
      this.saveImagesToMoblie()
    }
  },
  // 保存图片到手机
  saveImagesToMoblie() {
    this.data.imageList.forEach(item => {
      my.saveImage({
        url: item.imgUrl,
        success() {
          Toast.text({
            message: '保存成功,请前往相册查看'
          })
        }
      })
    })
  },
  handleDeleteImage(e) {
    this.setData({
      deleteImageId: e.target.dataset.id
    })
    this.handleDeleteDialogShow()
  },
  // 删除图片
  deleteImage() {
    let arr = this.data.imageList.filter(v => v.id !== this.data.deleteImageId)
    this.setImageList(arr)
    this.handleDeleteDialogShow()
  },
  // 选择图片
  chooseImages() {
    my.chooseImage({
      count: app.globalData.totalMax,
      success: res => {
        let arr = this.data.imageList
        res.apFilePaths.forEach((item, index) => {
          arr.push({
            id: new Date().getTime() + index,
            originImgUrl: item,
            imgUrl: item
          })
        })
        this.setImageList(arr)
      }
    })
  },
  // 更改图片列表
  setImageList(arr) {
    this.setData({
      imageList: arr
    })
    app.globalData.imageList = arr
  },
  // 编辑图片
  editImage(e) {
    my.navigateTo({
      url: `/pages/edit/index?id=${e.target.dataset.id}`
    })
  },
  // 绑定数据
  bindData() {
    this.setData({
      imageList: app.globalData.imageList,
      totalMin: app.globalData.totalMin,
      totalMax: app.globalData.totalMax
    })
  },
  handleSubmitDialogShow() {
    this.setData({
      submitDialogShow: !this.data.submitDialogShow
    })
  },
  handleDeleteDialogShow() {
    this.setData({
      deleteDialogShow: !this.data.deleteDialogShow
    })
  },
  setToastRef(ref) {
    new Toast(ref)
  },
  onShow(query) {
    this.bindData()
  }
})
